using System;
using JohnHolliday.Caml.Net;
using Microsoft.SharePoint;

namespace Camelot
{
    public class SearchCriteria
    {
        public Uri WebUrl { get; set; }

        public SPContentType ContentType { get; set; }

        public BaseTemplate BaseTemplate { get; set; }

        public SPListTemplate ListTemplate { get; set; }

        public string SearchScope { get; set; }

        public string ViewFields { get; set; }

        public SPSiteDataQuery GetQuery()
        {
            SPSiteDataQuery siteDataQuery = new SPSiteDataQuery();

            InitializeScopes(siteDataQuery);            
            InitializeQuery(siteDataQuery);
            InitializeLists(siteDataQuery);
            InitializeViewFields(siteDataQuery);
            return siteDataQuery;
        }

        private void InitializeViewFields(SPSiteDataQuery query)
        {
            if (!string.IsNullOrEmpty(this.ViewFields))
            {
                query.ViewFields = this.ViewFields;
            }
        }

        private void InitializeLists(SPSiteDataQuery query)
        {
            if (this.ListTemplate != null)
            {
                query.Lists = string.Format("<Lists ServerTemplate='{0}' Hidden='TRUE'/>", (int) this.ListTemplate.Type);
            }
            else if(this.BaseTemplate != null)
            {
                query.Lists = string.Format("<Lists BaseType='{0}' Hidden='TRUE'/>", (int)this.BaseTemplate.Type);
            }
        }

        private void InitializeScopes(SPSiteDataQuery query)
        {
            switch (this.SearchScope)
            {
                case "SiteCollection":
                case "Recursive":
                    query.Webs = string.Format("<Webs Scope='{0}' />", this.SearchScope);
                    break;                    
                default:
                    query.Webs = string.Empty;
                    break;                    
            }
        }

        private void InitializeQuery(SPSiteDataQuery siteDataQuery)
        {
            if (this.ContentType != null)
            {
                siteDataQuery.Query = GetCamlQuery(this.ContentType);
            }
        }

        /// <summary>
        /// Gets the caml query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <returns></returns>
        private string GetCamlQuery(SPContentType contentType)
        {
            return CAML.Where(
                        CAML.BeginsWith(
                            CAML.FieldRef("ContentTypeId"), CAML.Value(contentType.Id.ToString())));
        }
    }
}